from pyinotify import WatchManager, Notifier, ProcessEvent, EventsCodes
import time

class NameCollection(ProcessEvent):
    def my_init(self, callback):
        self.callback = callback
    def process_IN_CREATE(self, event):
        pass
    def process_default(self, event):
        self.callback(event.name)

class Monitor:
    def __init__(self, path, pattern, recursive=True, timeout=None):
        self.changes = False
        def check_changes(fn):
            self.changes |= bool(pattern.search(fn))
        option = {}
        if recursive:
            option = {'rec': True, 'auto_add': True}
        wm = WatchManager()
        wm.add_watch(path, mask=
                FLAGS['IN_CLOSE_WRITE'] |
                FLAGS['IN_MOVED_TO'] |
                FLAGS['IN_CREATE'],
                **option)
        p = NameCollection(callback=check_changes)
        self.notifier = Notifier(wm, p, timeout=timeout)
    def changed(self, sleeptime=0):
        if self.notifier.check_events():
            if sleeptime:
                time.sleep(sleeptime)
            self.notifier.read_events()
        self.changes = False
        self.notifier.process_events()
        return self.changes

FLAGS = EventsCodes.ALL_FLAGS
def mainloop(path, pattern, callback, recursive=True):
    callback()
    monitor = Monitor(path, pattern, recursive)
    while 1:
        if monitor.changed(0.1):
            callback()
